import { defineStore } from "pinia";
import { ref } from "vue";
import request from "@/utils/request";
import type {
  ApiRes,
  CategoryItem,
  SubCategory,
  TopCategory,
} from "@/types/data";
import { topCategory } from "../constants";

const defaultCategory = topCategory.map((item) => {
  return { name: item };
});

const useCategoryStore = defineStore("category", () => {
  //分类列表数据
  const list = ref(defaultCategory as CategoryItem[]);
  const getCategoryList = async () => {
    const { data: res } = await request.get<ApiRes<CategoryItem[]>>(
      "/home/category/head"
    );
    list.value = res.result;
  };

  // 根据id获取一级分类数据
  const topCategory = ref({} as TopCategory);
  const getTopCategory = async (id: string) => {
    const res = await request.get<ApiRes<TopCategory>>("/category?id=" + id);
    topCategory.value = res.data.result;
  };

  // 根据id获取二级分类数据
  const subCategory = ref({} as SubCategory);
  const getSubCategory = async (id: string) => {
    const res = await request.get<ApiRes<SubCategory>>(
      "/category/sub/filter?id=" + id
    );

    subCategory.value = res.data.result;
  };

  return {
    list,
    getCategoryList,
    topCategory,
    getTopCategory,
    subCategory,
    getSubCategory,
  };
});

export default useCategoryStore;
